#include "asteroid.h"

Asteroid::Asteroid(qint32 width, qint32 height)
{
    m_pixmap = QPixmap("img/asteroid.png");

    qint32 side = qrand() % 4;

    qreal toX = 0.0, toY = 1.0;

    switch (side)
    {
    case 0:
        m_y = -m_pixmap.height() / 2.0;
        m_x = qrand() % (m_pixmap.width() + width) - m_pixmap.width() / 2.0;

        toX = qrand() % (m_pixmap.width() + width) - m_pixmap.width() / 2.0;
        toY = height + m_pixmap.height() / 2.0;

        break;
    case 1:
        m_y = height + m_pixmap.height() / 2.0;
        m_x = qrand() % (m_pixmap.width() + width) - m_pixmap.width() / 2.0;

        toX = qrand() % (m_pixmap.width() + width) - m_pixmap.width() / 2.0;
        toY = -m_pixmap.height() / 2.0;

        break;
    case 2:
        m_y = qrand() % (m_pixmap.height() + height) - m_pixmap.height() / 2.0;
        m_x = -m_pixmap.width() / 2.0;

        toX = width + m_pixmap.width() / 2.0;
        toY = qrand() % (m_pixmap.height() + height) - m_pixmap.height() / 2.0;

        break;
    case 3:
        m_y = qrand() % (m_pixmap.height() + height) - m_pixmap.height() / 2.0;
        m_x = width + m_pixmap.width() / 2.0;

        toX = -m_pixmap.width() / 2.0;
        toY = qrand() % (m_pixmap.height() + height) - m_pixmap.height() / 2.0;

        break;
    }

    qreal angle = atan2(toY - m_y, toX - m_x);
    m_dirX = cos(angle);
    m_dirY = sin(angle);

    m_angle = qrand() % 360;
    m_angleSpeed = qrand() % 31 - 15;

    m_speed = qrand() % 100 / 10.0;
}

Asteroid::~Asteroid()
{

}

void Asteroid::draw(QPainter *painter)
{
    painter->translate(m_x, m_y);
    painter->rotate(m_angle);
    painter->drawPixmap(-m_pixmap.width() / 2.0, -m_pixmap.height() / 2.0, m_pixmap);
    painter->resetTransform();
}

void Asteroid::move()
{
    m_x += m_dirX * m_speed;
    m_y += m_dirY * m_speed;
    m_angle += m_angleSpeed;
}

bool Asteroid::isOutOfField(qint32 width, qint32 height)
{
    return m_x < -m_pixmap.width() / 2.0 || m_y < -m_pixmap.height() / 2.0 ||
            m_x > width + m_pixmap.width() / 2.0 || m_y > height + m_pixmap.height() / 2.0;
}

qreal Asteroid::getX()
{
    return m_x;
}

qreal Asteroid::getY()
{
    return m_y;
}

qreal Asteroid::getRadius()
{
    return m_pixmap.width() / 2.0;
}
